package query;



import java.util.Hashtable;
import java.util.StringTokenizer;

import document.StopWordLexicon;

public class QueryBuilder {

	
	public QueryBuilder() {
		stringToQuery = new Hashtable<String, QueryFactory>();
		stringToQuery.put("or", new QueryFactory() {
			public Query getQuery() {
				return new OrOperand();
			}
		});
		stringToQuery.put("and", new QueryFactory() {
			public Query getQuery() {
				return new AndOperand();
			}
		});
		stringToQuery.put("not", new QueryFactory() {
			public Query getQuery() {
				return new AndNotOperand();
			}
		});
	}


	public void parse(String query) {
		Query left = null;
		StringTokenizer token = new StringTokenizer(query, DELIMITERS);
		while (token.hasMoreTokens()) {
			String t = token.nextToken();
			if (stringToQuery.containsKey(t)) {
				Query temp = stringToQuery.get(t).getQuery();
				temp.putLeftOperand(left);
				left = temp;
			} else {
				Query temp;
				if(!StopWordLexicon.getInstance().isStopWord(t)) 
				{
					temp = new Term(t);
				}
				else
				{
					temp = new StopWord(t);
				}
				if (left == null) {
					left = temp;
				} else {
					left.putRightOperand(temp);
				}
				
			}
		}

		this.query = left;
	}

	public Query getQuery() {
		return query;
	}

	private Query query;
	private final String DELIMITERS = " \t\n\r\f,;.:;";
	private Hashtable<String, QueryFactory> stringToQuery;

	public interface QueryFactory {
		public Query getQuery();
	};
}
